package com.example.mymavendemo.controller;

import cn.hutool.core.map.MapUtil;
import com.example.mymavendemo.common.lang.Const;
import com.example.mymavendemo.common.lang.Result;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.UUID;
@RestController
public class AuthController extends BaseController{

    @Autowired
    Producer producer;
    @GetMapping("/captcha")
    public Result<?> captcha() throws IOException {
        String key= UUID.randomUUID().toString();
        String code=producer.createText();

        BufferedImage image=producer.createImage(code);
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",outputStream);

        Encoder encoder= Base64.getEncoder();
        String str="data:image/jpeg;base64";

        String base64Img = str + encoder.encodeToString(outputStream.toByteArray());

        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        return Result.success(
                MapUtil.builder()
                        .put("key",key)
                        .put("base64Img",base64Img)
                        .build()
        );
    }

}
